package com.sz.freemusic.net;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.sz.data.Artist;
import com.sz.freemusic.common.ApplicationData;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.http.AndroidHttpClient;
import android.util.Log;

public class HttpRetreiver {
	
	private static final String TAG = HttpRetreiver.class.getName();
	
	
	
	public static ArrayList<Artist> connect(String url)
	{
		ArrayList<Artist> artists = new ArrayList<Artist>();
		DataParser parser = new DataParser();
	    HttpClient httpclient = new DefaultHttpClient();

	    // Prepare a request object
	    HttpGet httpget = new HttpGet(url); 

	    // Execute the request
	    HttpResponse response;
	    try {
	        response = httpclient.execute(httpget);
	        // Examine the response status
	        Log.i(TAG,response.getStatusLine().toString());

	        // Get hold of the response entity
	        HttpEntity entity = response.getEntity();
	        // If the response does not enclose an entity, there is no need
	        // to worry about connection release

	        if (entity != null) {

	            // A Simple JSON Response Read
	            InputStream instream = entity.getContent();
	            String result= convertStreamToString(instream);
	            // now you have the string representation of the HTML request
	            artists = (ArrayList<Artist>) parser.parseArtists(result);
	            instream.close();
	        }


	    } catch (Exception e) {
	    	Log.e(TAG, "Exception when connecting: " + e);
	    }
	    return artists;
	}

	    private static String convertStreamToString(InputStream is) {
	    /*
	     * To convert the InputStream to String we use the BufferedReader.readLine()
	     * method. We iterate until the BufferedReader return null which means
	     * there's no more data to read. Each line will appended to a StringBuilder
	     * and returned as String.
	     */
	    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
	    StringBuilder sb = new StringBuilder();

	    String line = null;
	    try {
	        while ((line = reader.readLine()) != null) {
	            sb.append(line + "\n");
	        }
	    } catch (IOException e) {
	        e.printStackTrace();
	    } finally {
	        try {
	            is.close();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }
	    return sb.toString();
	}
	    
	    
	 public static Bitmap downloadBitmap(String url) {
	        final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
	        HttpGet getRequest = new HttpGet(url);
	        

	        try {
	            HttpResponse response = client.execute(getRequest);
	            
	            final int statusCode = response.getStatusLine().getStatusCode();
	            if (statusCode != HttpStatus.SC_OK) {
	            	if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
	            		Header[] location = response.getHeaders("Location");
	            		if (location != null && location.length > 0) {
	            			String newUrl = location[location.length - 1].getValue();
	            			getRequest = new HttpGet(newUrl);
	            			response = client.execute(getRequest);
	            		} else {
	    	                Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url); 
	    	                return null;			
	            		}
	            	}

	            }
	            
	            final HttpEntity entity = response.getEntity();
	            if (entity != null) {
	                InputStream inputStream = null;
	                try {
	                    inputStream = entity.getContent(); 
	                    final Bitmap bitmap = decodeSampledBitmapFromStream(inputStream, 48, 48); //ApplicationData.getInstance().getThWidth(), 
//	                    		ApplicationData.getInstance().getThHeight());
//	                    final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
	                    return bitmap;
	                } finally {
	                    if (inputStream != null) {
	                        inputStream.close();  
	                    }
	                    entity.consumeContent();
	                }
	            }
	        } catch (Exception e) {
	            // Could provide a more explicit error message for IOException or IllegalStateException
	            getRequest.abort();
	        } finally {
	            if (client != null) {
	                client.close();
	            }
	        }
	        return null;
	    }
	
	 public static int calculateInSampleSize(
	            BitmapFactory.Options options, int reqWidth, int reqHeight) {
	    // Raw height and width of image
	    final int height = options.outHeight;
	    final int width = options.outWidth;
	    int inSampleSize = 1;

	    if (height > reqHeight || width > reqWidth) {
	        if (width > height) {
	            inSampleSize = Math.round((float)height / (float)reqHeight);
	        } else {
	            inSampleSize = Math.round((float)width / (float)reqWidth);
	        }
	    }
	    return inSampleSize;
	}
	 
	 public static Bitmap decodeSampledBitmapFromStream(InputStream stream,
		        int reqWidth, int reqHeight) throws IOException {
		 	byte[] bytes = getBytes(stream);
		    // First decode with inJustDecodeBounds=true to check dimensions
		    final BitmapFactory.Options options = new BitmapFactory.Options();
		    options.inJustDecodeBounds = true;
		    BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
		    

		    // Calculate inSampleSize
		    options.inSampleSize = calculateInSampleSize(options, 48, 48);

		    // Decode bitmap with inSampleSize set
		    options.inJustDecodeBounds = false;
		    options.outHeight = 48;
		    options.outWidth = 48;
		    Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
		    
		    return bmp;
		}
	 
	 public static byte[] getBytes(InputStream is) throws IOException {

		    int len;
		    int size = 1024;
		    byte[] buf;

		    if (is instanceof ByteArrayInputStream) {
		      size = is.available();
		      buf = new byte[size];
		      len = is.read(buf, 0, size);
		    } else {
		      ByteArrayOutputStream bos = new ByteArrayOutputStream();
		      buf = new byte[size];
		      while ((len = is.read(buf, 0, size)) != -1)
		        bos.write(buf, 0, len);
		      buf = bos.toByteArray();
		    }
		    return buf;
		  }
}
